import * as vscode from "vscode";
import { GLOBAL_UI_SELECT_EXTENSION_ID } from "../config";

/**
 * @description 描述 用于管理 VS Code 状态栏项和选中行数的类
 * @date 2024-11-29 09:32:39
 * @author tingfeng
 */
export class SelectCountStatusBar {
  private statusBarItem: vscode.StatusBarItem;
  private extensionId: string;

  constructor() {
    this.extensionId = GLOBAL_UI_SELECT_EXTENSION_ID;
    this.statusBarItem = vscode.window.createStatusBarItem(
      vscode.StatusBarAlignment.Right,
      100
    );
    this.statusBarItem.command = this.extensionId;
  }

  /**
   * @description 描述 初始化选中行数
   * @date 2024-11-29 09:32:39
   * @author tingfeng
   *
   * @export
   * @param context
   */
  public initSelectCount(context: vscode.ExtensionContext) {
    const { subscriptions } = context;

    subscriptions.push(
      vscode.commands.registerCommand(this.extensionId, () => {
        const selectNum = this.getNumberOfNowSelectLines(
          vscode.window.activeTextEditor
        );
        vscode.window.showInformationMessage(`当前总共选中行数${selectNum}`);
      })
    );

    subscriptions.push(this.statusBarItem);

    subscriptions.push(
      vscode.window.onDidChangeActiveTextEditor(() =>
        this.updateStatusBarItem()
      )
    );
    subscriptions.push(
      vscode.window.onDidChangeTextEditorSelection(() =>
        this.updateStatusBarItem()
      )
    );

    this.updateStatusBarItem();
  }

  /**
   * @description 描述 更新当前选中的行数
   * @date 2024-11-29 09:30:07
   * @author tingfeng
   *
   * @export
   */
  private updateStatusBarItem(): void {
    const n = this.getNumberOfNowSelectLines(vscode.window.activeTextEditor);
    if (n > 0) {
      this.statusBarItem.text = `$(megaphone)你已经选中了${n} 行`;
      this.statusBarItem.show();
    } else {
      this.statusBarItem.hide();
    }
  }

  /**
   * @description 描述 获取当前选中的行数
   * @date 2024-11-29 09:30:15
   * @author tingfeng
   *
   * @export
   * @param [editor]
   * @returns
   */
  private getNumberOfNowSelectLines(editor?: vscode.TextEditor): number {
    let l = 0;
    if (editor) {
      l = editor.selections.reduce((pre, cur) => {
        return pre + cur.end.line - cur.start.line;
      }, 0);
    }
    return l;
  }
}
